import { Avatar, Dropdown, Layout, Menu } from "antd"
import React, { useState } from "react"
import { MenuFoldOutlined, MenuUnfoldOutlined, LogoutOutlined } from "@ant-design/icons"
import styles from "./index.module.scss"
import { ItemType } from "antd/lib/menu/hooks/useItems"
import { useHistory } from "react-router-dom"
import { MenuInfo } from "rc-menu/lib/interface"
import { connect, ConnectedProps } from "react-redux"
import { userType } from "@/types"

type Props = ConnectedProps<typeof connector>

const Header: React.FC<Props> = (props) => {
  const { userInfo } = props

  const history = useHistory()
  const [collapsed, setCollapsed] = useState(false)
  const [menuItemList] = useState<ItemType[]>([
    {
      key: "item-1",
      label: "退出登录",
      icon: <LogoutOutlined />,
      danger: true,
    },
  ])

  const logout = (detail: MenuInfo) => {
    if (detail.key === "item-1") {
      sessionStorage.removeItem("token")
      history.replace("/login")
    }
  }

  return (
    <Layout.Header className={styles.header} style={{ padding: "0 20px", backgroundColor: "#fff" }}>
      {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
        className: styles.trigger,
        style: { fontSize: "20px" },
        onClick: () => setCollapsed(!collapsed),
      })}

      <div className={styles["header-rg"]}>
        <Dropdown overlay={<Menu items={menuItemList} onClick={logout} />}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <Avatar size={40} style={{ color: "#f56a00", backgroundColor: "#fde3cf" }}>
              {(userInfo.username ?? "L").slice(0, 1)}
            </Avatar>
            <div className={styles["username"]}>{userInfo.username}</div>
          </div>
        </Dropdown>
      </div>
    </Layout.Header>
  )
}

// 连接 Redux Store
const connector = connect((state: userType) => ({ userInfo: state }))

export default connector(Header)
